<template>
  <div class="login">
    <van-nav-bar title="黑马头条-登陆" />
    <van-cell-group>
      <van-field
      v-model.trim="mobile"
      required
      label="手机号"
      :error-message= mobile_errmsg
      placeholder="请输入手机号" />
      <van-field v-model.trim="code"
      type="password"
      required
      label="密码"
      :error-message= code_errmsg
      placeholder="请输入密码" />
    </van-cell-group>
    <div class="btn-wrap">
      <van-button type="info" class="btn" @click="hLogin">登陆</van-button>
      <van-button type="info" class="btn" @click="test">测试</van-button>
    </div>
  </div>
</template>

<script>
import { login, getProfile } from '@/api/user.js'
export default {
  name: 'Login',
  data () {
    return {
      mobile: null,
      code: null,
      mobile_errmsg: '',
      code_errmsg: ''
    }
  },
  methods: {
    validata () {
      if (this.mobile === '') {
        this.mobile_errmsg = '手机号不能为空'
        return false
      } else {
        this.mobile_errmsg = ''
      }
      if (this.code === '') {
        this.code_errmsg = '密码不能为空'
        return false
      } else {
        this.code_errmsg = ''
      }
      return true
    },
    async test () {
      getProfile()
    },
    async hLogin () {
      if (!this.validata()) {
        return
      }
      this.$toast.loading({
        duration: 0,
        mask: true,
        message: '登陆中'
      })
      try {
        const res = await login(this.mobile, this.code)
        this.$toast.success('登陆成功')
        this.$store.commit('setTokenInfo', res.data.data)
        this.$router.push('/')
      } catch (error) {
        this.$toast.fail('登陆失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login {
  .btn-wrap {
    padding:20px;
    .btn {
      width: 100%;
      background-color: #6db4fb;
      color: #fff;
    }
  }
}
</style>
